package com.sens.utils;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;

import com.sens.alipay.Configure;
import com.sens.alipay.utils.AlipayUtils;
import com.sens.alipay.utils.SupportVersion;
import com.sens.bean.BaseJson;
import com.sens.common.ApplicationUtil;
import com.sens.common.Base64;
import com.sens.common.StringUtil;
import com.sens.commonui.PermissionUtil;
import com.sens.database.LiteOrmDBUtil;
import com.sens.exception.PermissionException;
import com.sens.ipc.alipay.IPCHelper;
import com.sens.ipc.alipay.hooker.Handle;
import com.sens.network.ApiByHttp;
import com.sens.network.ResponseCallback;
import com.sens.orderback.OrderBackApplication;
import com.sens.orderback.ui.activity.alipay.SettingActivity;
import com.sens.tables.AliPayConfig;
import com.sens.vo.AliPayOrderVo;
import com.yanzhenjie.nohttp.rest.Response;

public class AlipayTestHelper {
    private static final int TEST_PROGRESS_RUN_MONITOR = 101;
    private static final int TEST_PROGRESS_RUN_ALIPAY = 103;
    private static final int TEST_PROGRESS_USERID = 105;
    private static final int TEST_PROGRESS_HOST = 106;
    private static final int TEST_PROGRESS_ORDER = 107;
    private static final int TEST_PROGRESS_CONNECT = 108;

    private Activity activity;
    private AlipayLogFilter logFilter;
    private Handle handle;
    private NoticeLogListener listener;

    private String userId;

    private boolean selfStartAlipay;
    private boolean hasConnect;
    private boolean hasCollectionedOrder;

    public AlipayTestHelper(Activity a, NoticeLogListener l) {
        this.activity = a;
        this.listener = l;
        this.logFilter = new AlipayLogFilter() {
            @Override
            public void requestMonitor() {
                super.requestMonitor();
                AliPayConfig aliPayConfig = LiteOrmDBUtil.getGlobalDBUtil(activity).queryOne(AliPayConfig.class);
                if (aliPayConfig != null)
                    handle.setMonitor(aliPayConfig.getMonitorType());
            }

            @Override
            public void updateUserId(String userId) {
                AlipayTestHelper.this.userId = userId;
                if (StringUtil.isEmpty(userId)) {
                    logFilter.noticeMessage(StringUtil.createColorText(Color.RED, "未检测到支付宝用户ID，请主动登录支付宝"));
                } else {
                    super.updateUserId(userId);
                    testWithProgress(TEST_PROGRESS_USERID);
                }
            }

            @Override
            public void addOrder(AliPayOrderVo aliPayOrderVo) {
                super.addOrder(aliPayOrderVo);
                if ("1000100101".equals(aliPayOrderVo.getUserId())) {
                    hasCollectionedOrder = true;
                    testWithProgress(TEST_PROGRESS_ORDER);
                }
            }

            @Override
            public void noticeLog(CharSequence message) {
                super.noticeLog(message);
                if (listener != null) listener.noticeLog(message);
            }
        };
        this.handle = IPCHelper.getHookerHandle(activity, logFilter);
        this.logFilter.requestMonitor();
    }

    public interface NoticeLogListener {
        void noticeLog(CharSequence message);
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case TEST_PROGRESS_RUN_MONITOR:
                case TEST_PROGRESS_HOST:
                    testWithProgress(requestCode);
                    break;
            }
        }
    }

    public void clearLog() {
        logFilter.clearLog();
    }

    public void saveLog() {
        logFilter.saveLog();
    }

    public void unBind() {
        handle.unBind();
        activity = null;
        logFilter = null;
        handle = null;
        listener = null;
        userId = null;
    }

    public void startTest() {
        logFilter.noticeMessage("-----------------------测试-----------------------");
        userId = null;
        hasCollectionedOrder = false;
        hasConnect = false;
        testWithProgress(TEST_PROGRESS_RUN_MONITOR);
    }

    private void testWithProgress(int progress) {
        boolean collectionAble = test(progress);
        if (collectionAble != OrderBackApplication.getInstance().isAlipayCollectionAble())
            OrderBackApplication.getInstance().setAlipayCollectionAble(collectionAble);
    }

    private boolean test(int progress) {
        if (!testStep1(progress)) return false;
        if (!testStep2(progress)) return false;
        if (!testStep3(progress)) return false;
        if (!testStep4(progress)) return false;
        if (!testStep5(progress)) return false;
        if (!testStep6(progress)) return false;
        if (!testStep7(progress)) return false;
        if (!testStep8(progress)) return false;
        logFilter.noticeMessage(StringUtil.createBiggerColorText(Color.BLUE, "可以正常使用了！"));
        return true;
    }

    private boolean testStep1(int progress) {
        AliPayConfig aliPayConfig = LiteOrmDBUtil.getGlobalDBUtil(activity).queryOne(AliPayConfig.class);
        if (aliPayConfig == null || StringUtil.isEmpty(aliPayConfig.getMonitorType())) {
            logFilter.noticeMessage("第一步：检查采集方式");
            logFilter.noticeMessage(StringUtil.createColorText(Color.RED, "还未设置采集方式"));
            ToastUtil.showToast("请设置采集方式");
            activity.startActivityForResult(new Intent(activity, SettingActivity.class), TEST_PROGRESS_RUN_MONITOR);
            return false;
        } else if (progress <= TEST_PROGRESS_RUN_MONITOR) {
            logFilter.noticeMessage("第一步：检查采集方式");
            for (int i = 0; i < Configure.monitors.length; i++) {
                if (Configure.monitorNames[i].equals(aliPayConfig.getMonitorType())) {
                    handle.setMonitor(Configure.monitors[i]);
                    break;
                }
            }
            logFilter.noticeMessage(StringUtil.createColorText(Color.BLUE, "采集方式:" + aliPayConfig.getMonitorType()));
        }
        return true;
    }

    private boolean testStep2(int progress) {
        if (!AlipayUtils.checkInstalled(activity)) {
            logFilter.noticeMessage("第二步：检查支付宝是否安装");
            logFilter.noticeMessage(StringUtil.createColorText(Color.RED, "支付宝未安装"));
            return false;
        } else if (progress <= TEST_PROGRESS_RUN_MONITOR) {
            logFilter.noticeMessage("第二步：检查支付宝是否安装");
            logFilter.noticeMessage(StringUtil.createColorText(Color.BLUE, "支付宝已安装"));
        }
        return true;
    }

    private boolean testStep3(int progress) {
        try {
            if (!AlipayUtils.isRunning(activity)) {
                logFilter.noticeMessage("第三步：检查支付宝是否运行");
                logFilter.noticeMessage(StringUtil.createColorText(Color.RED, "支付宝未运行"));
                ToastUtil.showToast("开始启动支付宝");
                selfStartAlipay = true;
                AlipayUtils.startAlipay(activity);
                activity.getWindow().getDecorView().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (selfStartAlipay) {
                            selfStartAlipay = false;
                            try {
                                if (AlipayUtils.isRunning(activity)) {
//                                    activity.startActivity(new Intent(activity, activity.getClass()));
                                    ApplicationUtil.moveToTop(activity);
                                    testWithProgress(TEST_PROGRESS_RUN_ALIPAY);
                                }
                            } catch (PermissionException e) {
                                if (e.getPermissionType() == PermissionException.PERMISSION_TYPE_OPERATION)
                                    requestOperationPermissions(e);
                            }
                        }
                    }
                }, 5000);
                return false;
            } else if (progress <= TEST_PROGRESS_RUN_ALIPAY) {
                logFilter.noticeMessage("第三步：检查支付宝是否运行");
                logFilter.noticeMessage(StringUtil.createColorText(Color.BLUE, "支付宝已运行"));
            }
        } catch (PermissionException e) {
            if (e.getPermissionType() == PermissionException.PERMISSION_TYPE_OPERATION)
                requestOperationPermissions(e);
            logFilter.noticeMessage("第三步：检查支付宝是否运行");
            logFilter.noticeMessage("请授予重要权限");
            return false;
        }
        return true;
    }

    private void requestOperationPermissions(PermissionException e) {
        PermissionUtil.requestOperationPermissions(activity, new PermissionUtil.OnPermissionCallback() {
            @Override
            protected void onGranted() {
                testWithProgress(TEST_PROGRESS_RUN_ALIPAY);
            }
        }, e.getMessage());
    }

    private boolean testStep4(int progress) {
        if (progress <= TEST_PROGRESS_RUN_ALIPAY) {
            logFilter.noticeMessage("第四步：检查支付宝版本");
            String versionName = ApplicationUtil.getVersionName(activity, new String(Base64.decode("Y29tLmVnLmFuZHJvaWQuQWxpcGF5R3Bob25l")));
            if (SupportVersion.checkSupportable(versionName))
                logFilter.noticeMessage(StringUtil.createColorText(Color.BLUE, "支付宝版本:" + versionName));
            else {
                logFilter.noticeMessage(StringUtil.createColorText(Color.RED, "支付宝版本:" + versionName));
                logFilter.noticeMessage(StringUtil.createColorText(Color.RED, "暂不支持当前支付宝版本,支持列表:" + SupportVersion.getSupportVersion()));
                return false;
            }
        }
        return true;
    }

    private boolean testStep5(int progress) {
        if (StringUtil.isEmpty(this.userId)) {
            logFilter.noticeMessage("第五步：获取支付宝用户ID");
            handle.checkUserId();
            return false;
        }
        return true;
    }

    private boolean testStep6(int progress) {
        if (StringUtil.isEmpty(ApiByHttp.getInstance().getHost())) {
            logFilter.noticeMessage("第六步：检查服务器地址");
            logFilter.noticeMessage(StringUtil.createColorText(Color.RED, "服务器地址未设置"));
            ToastUtil.showToast("请设置服务地址");
            activity.startActivityForResult(new Intent(activity, SettingActivity.class), TEST_PROGRESS_HOST);
            return false;
        } else if (progress <= TEST_PROGRESS_HOST) {
            logFilter.noticeMessage("第六步：检查服务器地址");
            logFilter.noticeMessage(StringUtil.createColorText(Color.BLUE, "服务器地址已设置"));
        }
        return true;
    }

    private boolean testStep7(int progress) {
        if (!hasCollectionedOrder) {
            logFilter.noticeMessage("第七步：模拟数据");
            handle.test();
            return false;
        }
        return true;
    }

    private boolean testStep8(int progress) {
        if (!hasConnect) {
            logFilter.noticeMessage("第八步：检查服务器连接状态");
            ApiByHttp.getInstance().uploadAlipayOrder(null, new ResponseCallback<BaseJson>() {
                @Override
                public void onSucceed(int what, Response<BaseJson> response) {
                    super.onSucceed(what, response);
                    BaseJson baseJson = response.get();
                    if (baseJson != null)
                        if (baseJson.getStatus() == 1) {
                            logFilter.noticeMessage(StringUtil.createColorText(Color.BLUE, baseJson.getMsg()));
                            hasConnect = true;
                            testWithProgress(TEST_PROGRESS_CONNECT);
                        } else {
                            logFilter.noticeMessage(StringUtil.createColorText(Color.RED, baseJson.getMsg()));
                        }
                    else logFilter.noticeMessage(StringUtil.createColorText(Color.RED, "服务器连接失败"));
                }

                @Override
                public void onFailed(int what, Response<BaseJson> response) {
                    super.onFailed(what, response);
                    logFilter.noticeMessage(StringUtil.createColorText(Color.RED, "服务器连接失败"));
                }
            });
            return false;
        }
        return true;
    }
}
